import smtplib
import traceback
from contextlib import contextmanager
from email.message import EmailMessage

common_port = {"ssl": 465, "normal": 25}


@contextmanager
def smtp_client(host, port, username, password, use_ssl=True):
    if isinstance(port, str):
        port = int(port)

    smtp = None
    try:
        smtp = smtplib.SMTP_SSL(host=host, port=port) if use_ssl else smtplib.SMTP(host=host, port=port)
        smtp.login(username, password)
        yield smtp
    finally:
        if smtp:
            smtp.__exit__()


def check_email_server(host, port, username, password, use_ssl=True):
    """
    检查邮件的有效性
    :return check status, error reason
    """
    try:
        with smtp_client(host, port, username, password, use_ssl) as smtp:
            smtp.helo()
    except Exception as e:
        return False, f"{e.__class__}::{e}"
    return True, None


def send_email(host, port, from_addr, password, display_name, to_addr, subject, body, use_ssl=True):
    # TODO 需求方的需求，后期需优化
    msg = EmailMessage()
    msg['Subject'] = subject
    msg['From'] = f"{display_name} <{from_addr}>" if display_name else from_addr
    msg['To'] = to_addr
    msg.set_content(body, subtype="html")
    try:
        with smtp_client(host, port, from_addr, password, use_ssl) as smtp:
            smtp.send_message(msg)
    except Exception as e:
        return False, f"{e.__class__}::{e}, details:\n{traceback.format_exc()}"
    return True, None
